<!--  -->
<template>
  <view class="scan-operate">
    <qrcode-stream
      class="qrcode-wrap"
      :torch="torch"
      v-memo="[torch]"
      :constraints="selectedConstraints"
      :track="paintBoundingBox"
      @error="onError"
      @detect="onDetect"
      @camera-on="onCameraReady"
    >
    </qrcode-stream>
  </view>
</template>

<script setup>
import { QrcodeStream } from 'vue-qrcode-reader';

import { onMounted, onUnmounted, ref } from 'vue';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
const main = useMainStore();
const { currentLanguageTexts } = storeToRefs(main);
const error = ref('');
const cameraIsReady = ref(false);
const isSupportTorch = ref(false); // 是否支持闪光灯
const torch = ref(false); // 闪光灯状态
// 相机配置选项: 'user'|'environment' （默认：environment）
const selectedConstraints = ref({ facingMode: 'environment' });

// 检测到二维码后绘制画布类型
function paintBoundingBox(detectedCodes, ctx) {
  for (const detectedCode of detectedCodes) {
    const {
      boundingBox: { x, y, width, height },
    } = detectedCode;

    ctx.lineWidth = 2;
    ctx.strokeStyle = '#007bff';
    // 绘制边框矩形
    ctx.strokeRect(x, y, width, height);
  }
}
async function onCameraReady(capabilities) {
  // NOTE: on iOS we can't invoke `enumerateDevices` before the user has given
  // camera access permission. `QrcodeStream` internally takes care of
  // requesting the permissions. The `camera-on` event should guarantee that this
  // has happened.
  try {
    isSupportTorch.value = !!capabilities.torch;
    cameraIsReady.value = true;
    error.value = '';
  } catch (error) {
    onError(error);
    cameraIsReady.value = false;
  }
}
// 错误提示
function onError(err) {
  error.value = `[${err.name}]: `;
  if (err.name === 'NotAllowedError') {
    error.value += 'you need to grant camera access permission';
  } else if (err.name === 'NotFoundError') {
    error.value += 'no camera on this device';
  } else if (err.name === 'NotSupportedError') {
    error.value += 'secure context required (HTTPS, localhost)';
  } else if (err.name === 'NotReadableError') {
    error.value += 'is the camera already in use?';
  } else if (err.name === 'OverconstrainedError') {
    error.value += 'installed cameras are not suitable';
  } else if (err.name === 'StreamApiNotSupportedError') {
    error.value += 'Stream API is not supported in this browser';
  } else if (err.name === 'InsecureContextError') {
    error.value +=
      'Camera access is only permitted in secure context. Use HTTPS or localhost rather than HTTP.';
  } else {
    error.value += err.message;
  }
  uni.showToast({
    title: error.value,
    icon: 'none',
  });
}
// 用户摄像头的流后
function onDetect(detectedCodes) {
  if (detectedCodes.length > 0) {
    uni.showToast({
      title: currentLanguageTexts.value.scanSuccess,
      icon: 'success',
    });
    location.href = detectedCodes[0]?.rawValue;
  }
}

onMounted(() => {});
onUnmounted(() => {});
</script>

<style lang="scss" scoped>
.scan-operate {
  height: 100%;
  width: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  .reader {
    height: 100%;
    width: 100%;
  }
}
</style>
